from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
import base64

# 固定公钥Base64字符串
_PUBLIC_KEY_B64 = (
    "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDBgxenWGQrynpHxvRsnlXWBFCr"
    "Ghf3eES3/aajLV+oceh1m4xZyUSA5mMoRvdvfmo+snVPuGPTwzz4MP1xLSgEtcQRz"
    "l1atza0Kt106HBKihKqhqJsLTSRE0xiGcZJMPpcpho/xLI+T3nmsHwQTMQD+TAgmz"
    "LBnffs6Hoart6FPQIDAQAB"
)

def rsa_encrypt(message: str) -> str:
    """
    使用写死的RSA公钥加密明文，并返回Base64密文字符串。
    """
    # 1. DER解码+PEM格式组装
    der_data = base64.b64decode(_PUBLIC_KEY_B64)
    pem = b"-----BEGIN PUBLIC KEY-----\n" + \
        base64.encodebytes(der_data).replace(b'\n\n', b'\n') + \
        b"-----END PUBLIC KEY-----\n"
    # 2. 加载公钥
    pubkey_obj = serialization.load_pem_public_key(pem)
    # 3. 加密
    ciphertext = pubkey_obj.encrypt(
        message.encode('utf-8'),
        padding.PKCS1v15()
    )
    # 4. Base64编码密文
    return base64.b64encode(ciphertext).decode("utf-8")

# 示例
if __name__ == "__main__":
    s = '你好，这是RSA加密测试'
    print(rsa_encrypt(s))